package tech.edwardvan.springsecuritydemo.security.handler;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import tech.edwardvan.springsecuritydemo.common.ResponseCode;
import tech.edwardvan.springsecuritydemo.common.ServerResponse;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Jwt认证失败处理器
 *
 * @author EdwardVan
 */
public class JwtAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServerResponse serverResponse = new ServerResponse(ResponseCode.UNAUTHORIZED.getCode(), ResponseCode.UNAUTHORIZED.getDesc(), exception != null ? exception.getMessage() : null);
        IoUtil.writeUtf8(response.getOutputStream(), true, JSONUtil.toJsonStr(serverResponse));
    }
}
